package com.sse.product.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sse.product.rbac.entity.Menus;
import com.sse.product.rbac.entity.Role;
import com.sse.product.rbac.entity.RoleMenus;
import com.sse.product.exception.BizRuntimeException;
import com.sse.product.rbac.mapper.MenusMapper;
import com.sse.product.rbac.mapper.RoleMenusMapper;
import com.sse.product.rbac.service.IMenusService;
import com.sse.product.rbac.service.IRoleMenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author junyongli
 * @since 2022-07-22
 */
@Service
public class RoleMenusServiceImpl extends ServiceImpl<RoleMenusMapper, RoleMenus>  implements IRoleMenusService {
    @Autowired
    private IMenusService menuService;
    @Autowired
    private RoleMenusMapper roleMenusMapper;
    @Autowired
    private MenusMapper menusMapper;

    @Override
    public List<Menus> queryMenuByRoleId(Long roleId) {
        List<RoleMenus> roleMenusList = roleMenusMapper.selectList(
                new LambdaQueryWrapper<RoleMenus>()
                        .eq(RoleMenus::getRoleId,roleId)
                        .orderByAsc(RoleMenus::getId));
        List<Long> menuIds = roleMenusList.stream().map(RoleMenus::getMenuId).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(menuIds))
          return menuService.listByIds(menuIds);
        else
          return new ArrayList<>();
    }

    @Override
    @Transactional
    public Boolean addRoleMenu(Role role, List<Menus> menusList) {
        roleMenusMapper.deleteById(role.getId());

        List<RoleMenus> roleMenusList =new ArrayList<>();

        menusList.stream().forEach(menu -> {
            Menus menus = menusMapper.selectOne(new LambdaQueryWrapper<Menus>().eq(Menus::getUniqueName, menu.getUniqueName()));
            if (Objects.nonNull(menus)) {
                roleMenusList.add(new RoleMenus(role.getId(),menus.getId()));
            } else {
                throw new BizRuntimeException("对应的菜单uniqueName:" + menu.getUniqueName() + "系统中不存在!");
            }
        });

        return saveBatch(roleMenusList);
    }
}
